<template>
  <div>
    <common-head title="联系人列表" />
    <div class="wrap">
      <van-address-list
        v-model="chosenAddressId"
        :list="list"
        default-tag-text="默认"
        @add="onAdd"
        @edit="onEdit"
        @select="choseContact"
      />
    </div>
  </div>
</template>

<script>
import CommonHead from 'components/CommonHead'
import { fetchContacts } from 'api'
import { getToken } from 'utils'
export default {
  data () {
    return {
      chosenAddressId: -1,
      list: []
    }
  },
  created () {
    this.fetchContacts()
  },
  beforeRouteEnter (to, from, next) {
    localStorage.setItem('from', from.path)
    next()
  },
  methods: {
    choseContact (contact, index) {
      // 联系人切换
      const from = localStorage.getItem('from')
      console.log(from, '/path')
      if (from === '/confirmorder') {
        // 确认从订单页过来
        this.$router.push({
          path: from,
          query: {
            id: contact.id
          }
        })
      }
    },
    onAdd () {
      this.$router.push('/contactAdd')
    },
    onEdit (contact) {
      this.$router.push({
        path: '/contactupdate',
        query: {
          id: contact.id
        }
      })
    },
    fetchContacts () {
      fetchContacts({
        token: getToken()
      }).then(res => {
        console.log(res)
        if (res.data.code === 0) {
          const contacts = res.data.data.result
          const contactArr = []
          contacts.forEach(contact => {
            // 循环遍历每个联系人 所有key
            const obj = {}
            for (const key in contact) {
              switch (key) {
                case 'id':
                  obj.id = contact[key]
                  break
                case 'address':
                  obj.address = contact[key]
                  break
                case 'linkMan':
                  obj.name = contact[key]
                  break
                case 'mobile':
                  obj.tel = contact[key]
                  break
                case 'isDefault':
                  obj.isDefault = contact[key]
                  break
                default:
                  break
              }
            }
            contactArr.push(obj)
          })
          this.list = contactArr
          const contact = this.list.find(contact => contact.isDefault)
          if (contact) {
            this.chosenAddressId = contact.id
          } else {
            this.chosenAddressId = this.list[0].id
          }
        }
      })
    }
  },
  components: {
    CommonHead
  }
}
</script>
<style lang="scss" scoped>
.custom-image .van-empty__image {
  width: 90px;
  height: 90px;
}
</style>
